package com.example.aircraftwar.codes.application.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import com.example.aircraftwar.R;

public class MusicService extends Service {
    private String videoName;
    private boolean videoOpen;

    public MusicService() {
    }

    //创建播放器对象
    private MediaPlayer player;
    public int onStartCommand(Intent intent, int flags, int startId) {
        videoName = intent.getStringExtra("videoName");
        videoOpen = intent.getBooleanExtra("videoOpen",false);
        if(videoOpen) {
            //播放
            playMusic();
        }
        if (!videoOpen) {
            //停止
            stopMusic();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //播放音乐
    public void playMusic(){
        if(player == null){
            if(videoName.equals("bgm")){
                player = MediaPlayer.create(this, R.raw.bgm);
            }
            if(videoName.equals("boss")){
                player = MediaPlayer.create(this, R.raw.bgm_boss);
            }
        }
        player.setLooping(true);
        player.start();
    }

    //停止播放
    public void stopMusic() {
        if (player != null) {
            player.stop();
            player.reset();//重置
            player.release();//释放
            player = null;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopMusic();
    }
}